<?php
/**
 * Created by PhpStorm.
 * User: 65736
 * Date: 2018/7/25 0025
 * Time: 20:43
 */

namespace app\common\library;


use app\common\service\AesOpenssl;
use http\Env\Request;
use Imagick;
use ReflectionClass;
use Requests;
use think\Cache;
use think\Config;
use think\Exception;
use think\Log;

class CommonFun
{
    /**
     * 抛出异常并写入日志
     * @param $message
     * @param bool $write_log
     * @throws Exception
     */
    public static function make_exception($message, $write_log = true)
    {
        if ($write_log) {
            Log::write($message, Log::ERROR);
        }
        throw new Exception($message);
    }

    /**
     * 加载其他配置文件
     * @param string $config_name 配置文件名称
     * @param int $type 配置类型, 1:项目(项目中的配置文件) 2:应用(应用目录application/common/config/)
     * @return mixed
     * @throws Exception
     */
    public static function get_other_config($config_name, $type = 1)
    {
        // 检测配置名称是否合法
        $pattern = '/[a-z_]+/';
        if (!preg_match($pattern, $config_name)) {
            // 格式不匹配
            self::make_exception("配置文件名称格式不正确!");
        }
        $filepath = "";
        if ($type == 1) {
            // 加载项目配置
            !defined("ModuleName") && self::make_exception("模块未定义常量ModuleName");

            $filepath = APP_PATH . ModuleName . DS . $config_name . CONF_EXT;
        } elseif ($type == 2) {
            $filepath = ENV_CONF_PATH . $config_name . CONF_EXT;
            if (!file_exists($filepath)) $filepath = CONF_PATH . $config_name . CONF_EXT;
        } else {
            // 类型不存在
            self::make_exception("配置文件类型不存在!");
        }

        if (!file_exists($filepath)) self::make_exception("配置文件不存在[{$config_name}]!");

        return Config::load($filepath);
    }

    /**
     * 获取图片配置
     * @param string $type 配置类型名称
     * @return array
     * @throws Exception
     */
    public static function get_image_config($type)
    {
        self::get_other_config('ImageSizeConfig', 2);
        $image_config = Config::get("image_config.{$type}");
        return $image_config ?: [];
    }

    /**
     * 求两个数的最大公约数
     * @param int $a
     * @param int $b
     * @return int
     */
    public static function max_divisor_with_two_nums($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            return self::max_divisor_with_two_nums($b, ($a % $b));
        }
    }

    /**
     * Json_encode改进, 自动escape中文
     * @param array|object $res
     * @return string
     */
    public static function json_encode2($res)
    {
        return json_encode($res, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取Memcache缓存对象
     * @param string $config_name Memcache缓存配置名称
     * @return \app\common\driver\cache\Memcached|\Memcached|\think\cache\Driver
     */
    public static function get_memcache($config_name)
    {
        $cache = Cache::store($config_name);
        return $cache;
    }

    /**
     * 获取Redis对象
     * @param $config_name
     * @return \Redis|\think\cache\Driver|\app\common\driver\cache\Redis
     */
    public static function get_redis($config_name)
    {
        $cache = Cache::store($config_name);
        return $cache;
    }

    /**
     * 数组按字段排序
     * @param array $ori_array 原始数组 (按址传递)
     * @param string $sort_field 排序字段
     * @param string $sequence 排序规则 ASC:升序 DESC:降序[默认]
     * @param bool $keep_ori_key 是否保持原始key
     * @param int $sortFlag 排序字段类型
     * @return array
     */
    public static function array_sort(&$ori_array, $sort_field, $sequence = 'DESC', $keep_ori_key = false, $sortFlag = SORT_REGULAR)
    {
        if ($keep_ori_key) {
            $sortData = array();
            foreach ($ori_array as $key => $value) {
                $sortData[$key] = $value[$sort_field];
            }
            ($sequence == 'DESC') ? arsort($sortData, $sortFlag) : asort($sortData, $sortFlag);
            $ret = array();
            foreach ($sortData as $key => $value) {
                $ret[$key] = $ori_array[$key];
            }
            $ori_array = $ret;
        } else {
            // 取出排序字段列, 以原始key为sort_data的key
            $sort_data = self::i_array_column($ori_array, $sort_field);
            // 判断排序规则
            $seq = $sequence == "DESC" ? SORT_DESC : SORT_ASC;
            // 多重排序
            array_multisort($sort_data, $seq, $sortFlag, $ori_array);
        }

        return $ori_array;
    }

    /**
     * array_column 替代方案
     * @param array $input 输入数组
     * @param string $columnKey 列字段
     * @param string $indexKey Key字段
     * @return array
     */
    public static function i_array_column($input, $columnKey, $indexKey = null)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array)$input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }

    /**
     * 用户密码加密方法
     * 使用password_hash的PASSWORD_BCRYPT算法cost为10
     * 使用password_verify验证密码
     * @param string $pwd 原始密码
     * @return string
     */
    public static function user_password_encrypt($pwd)
    {
        //$key = C('AUTH_KEY_CODE');
        //$str = md5($pwd.'_'.$key);
        $options = [
            'cost' => 10,
        ];
        $hash = password_hash($pwd, PASSWORD_BCRYPT, $options);
        return $hash;
    }

    /**
     * 验证用户密码
     * @param string $pwd 原始密码
     * @param string $hash hash值(数据库存储的hash值)
     * @return bool
     */
    public static function user_password_verify($pwd, $hash)
    {
        $res = password_verify($pwd, $hash);
        return $res;
    }

    /**
     * 获取13位时间戳(毫秒级)
     */
    public static function get_microtime_13()
    {
        $m = microtime(true);
        $m = $m * 1000;
        $m = round($m);
        return $m;
    }

    /**
     * 获取对象的类名称
     * @param object $object 对象实体
     * @param bool $withNameSpace 是否包含命名空间
     * @return string
     */
    public static function get_class_name($object, $withNameSpace = false)
    {
        $class = get_class($object);
        if (!$withNameSpace) {
            $exArr = explode("\\", $class);
            $class = end($exArr);
        }
        return $class;
    }

    /**
     * 判断一个数组是否是一个索引数组
     * @param array $array
     * @return bool true:索引 false关联
     */
    public static function array_is_assoc(array $array)
    {
        ksort($array, SORT_NATURAL);
        list($key) = self::func_new_each($array);
        return $key === 0 ? true : false;
    }

    /**
     * 由于PHP7.2版本废除each函数, 这里是each的替代函数
     * @param $array
     * @return array|bool
     */
    public static function func_new_each(&$array)
    {
        $res = array();
        $key = key($array);
        if ($key !== null) {
            next($array);
            $res[1] = $res['value'] = $array[$key];
            $res[0] = $res['key'] = $key;
        } else {
            $res = false;
        }
        return $res;
    }

    /**
     * 获取类的所有方法
     * @param string $class 类名称
     * @return array
     * @throws \ReflectionException
     */
    public static function get_class_all_methods($class) {
        $reflc = new ReflectionClass($class);
        $all_methods = $reflc->getMethods();
        $methods = array();
        foreach ( $all_methods as $key=>$method ) {
            if ( $method->isprivate() ) {
                $type = 'private';
            }elseif ( $method->isprotected() ) {
                $type = 'protected';
            }else  {
                $type = 'public';
            }
            $methods[$key]['type'] = $type;
            $methods[$key]['name'] = $method->name;
            $methods[$key]['class'] = $method->class;
            $methods[$key]['doc'] = $method->getDocComment();
        }
        return $methods;
    }

    /**
     * 生成唯一标示
     * @return string
     */
    public static function create_unique_id()
    {
        mt_srand(( double )microtime() * 1000000);
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);
        $uuid = '' . //chr(123)// "{"
            substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
        //.chr(125);// "}"
        return $uuid;
    }

    /**
     * 取得对象实例 支持调用类的静态方法
     * @param string $name 类名
     * @param string $method 方法名，如果为空则返回实例化对象
     * @param array $args 调用参数
     * @return mixed
     */
    public static function get_instance_of($name, $method = '', $args = array())
    {
        static $_instance = array();
        $identify = empty($args) ? $name . $method : $name . $method . self::to_guid_string($args);
        if (!isset($_instance[$identify])) {
            if (class_exists($name)) {
                $o = new $name();
                if (method_exists($o, $method)) {
                    if (!empty($args)) {
                        $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
                    } else {
                        $_instance[$identify] = $o->$method();
                    }
                } else
                    $_instance[$identify] = $o;
            } else
                halt('Class not exist' . ':' . $name);
        }
        return $_instance[$identify];
    }

    /**
     * 根据PHP各种类型变量生成唯一标识号
     * @param mixed $mix
     * @return string
     */
    public static function to_guid_string($mix)
    {
        if (is_object($mix) && function_exists('spl_object_hash')) {
            return spl_object_hash($mix);
        } elseif (is_resource($mix)) {
            $mix = get_resource_type($mix) . strval($mix);
        } else {
            $mix = serialize($mix);
        }
        return md5($mix);
    }

    /**
     * 处理显示几天前,几小时前,几分钟前
     * @param $the_time
     * @return string
     */
    public static function day_fast($the_time)
    {
        //$now_time = date("Y-m-d H:i:s", time() );
        //$now_time = strtotime($now_time);
        $now_time = time();
// 		if ( self::is_valid_time($the_time) ) {
// 			// 日期格式
// 			$show_time = strtotime($the_time);
// 		}
        $dur = $now_time - $the_time;
        if ($dur <= 0) {
            return '刚刚';
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 604800) {//7天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            if ($dur < 2419200) {
                                return floor($dur / 604800) . '周前';
                            } else {
                                if ($dur < 31536000) {
                                    return floor($dur / 2419200) . '月前';
                                } else {
                                    return floor($dur / 31536000) . '年前';
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 截取字符串
     * @param $text
     * @param $length
     * @return string
     */
    public static function subtext($text, $length)
    {
        if (mb_strlen($text, 'utf8') > $length)
            return mb_substr($text, 0, $length, 'utf8') . '...';
        return $text;
    }

    /**
     * 格式化价格
     * @param $price
     * @param int $decimals
     * @param string $decimalpoint
     * @param string $separator
     * @return string
     */
    public static function price_format($price, $decimals = 2, $decimalpoint = '.', $separator = '')
    {
        return number_format($price, $decimals, $decimalpoint, $separator);
    }

    /**
     * 返回数字+亿/万
     * @param $num
     * @return int|string
     */
    public static function fromate_num_unit($num)
    {
        if (is_nan((float)$num)) {
            return 0;
        }
        if ($num == 0) {
            return $num;
        } else {
            if ($num < 10000) {
                return $num;
            } else {
                if ($num < 100000000) {
                    return floor($num / 10000) . '万';
                } else {
                    return floor($num / 100000000) . '亿';
                }
            }
        }
    }

    /**
     * 去掉小数后面多余的0
     * @param $s
     * @return null|string|string[]
     */
    public static function del_float_str_zero($s)
    {
        $s = trim(strval($s));
        if (preg_match('#^-?\d+?\.0+$#', $s)) {
            return preg_replace('#^(-?\d+?)\.0+$#', '$1', $s);
        }
        if (preg_match('#^-?\d+?\.[0-9]+?0+$#', $s)) {
            return preg_replace('#^(-?\d+\.[0-9]+?)0+$#', '$1', $s);
        }
        return $s;
    }

    /**
     * 展示价格
     * @param $price
     * @param int $decimals
     * @param string $separator
     * @return mixed|string
     */
    public static function price_display_format($price, $decimals = 2, $separator = ',')
    {
        if ($decimals > 2) {
            $number_formate = self::price_format($price, $decimals);
            $number_formate = self::del_float_str_zero($number_formate);
            if (false === strpos($number_formate, ".")) {
                //没出现小数点, 再次格式化
                $number_formate = self::price_display_format($number_formate, 2, $separator);
            } else {
                list($a, $b) = explode(".", $number_formate);
                if ($b < 10 && strlen($b) == 1) {
                    $b = $b . "0";
                }
                $number_formate = $a . "." . $b;
                $b_strlen = strlen($b);
                $decimals = $b_strlen >= 2 ? $b_strlen : 2;
                $number_formate = self::price_format($number_formate, $decimals, '.', $separator);
            }
        } else {
            $number_formate = self::price_format($price, $decimals, '.', $separator);
        }
        return $number_formate;
    }

    /**
     * 版本号转换int
     * @param $version
     * @return int
     */
    public static function version_to_long($version)
    {
        // 获取版本号占有位数
        $version_count = count(explode(".", $version));
        $start_version = $version;

        while ($version_count < 4) {
            $start_version .= ".0";
            $version_count++;
        }

        $version_int = ip2long($start_version);
        return $version_int;
    }

    /**
     * 使用ECB模式加密, 并且通过base64_encode转化
     * @param $string
     * @param $key
     * @return string
     * @throws \Exception
     */
    public static function encrypt_ecb($string, $key)
    {
        if (PHP_VERSION_ID <= 70099 && extension_loaded('mcrypt')) {
            $block = mcrypt_get_block_size('des', 'ecb');
            $pad = $block - (strlen($string) % $block);
            $string .= str_repeat(chr($pad), $pad);
            $mc_str = mcrypt_encrypt(MCRYPT_DES, $key, $string, MCRYPT_MODE_ECB);
            return base64_encode($mc_str);
        } elseif (extension_loaded('openssl')) {
            $aes = new AesOpenssl($string, $key);
            return $aes->encrypt();
        } else {
            self::make_exception("openssl或mcrypt 扩展不存在");
        }

        return "";
    }

    /**
     * 判断一个绝对值小于1的小数有效数字之前0的个数 例如:0.1=>1 0.01=>2
     * @param $num
     * @return int
     */
    public static function count_zero_decimal_less_one($num)
    {
        $abs = abs($num);
        if ($abs >= 1) {
            return 0;
        }
        // 格式化为科学计数法
        $_num = sprintf("%e", $abs);
        $res = preg_match("/.*?e-(\d)/", $_num, $match);
        if ($res > 0) {
            return $match[1];
        }
        return 0;
    }

    /**
     * BTC价格格式化(聪sat)
     * @param $price
     * @return mixed|string
     */
    public static function price_btc_display_formate($price)
    {
        if ($price < 1) {
            // 小于1的时候, 先判断有效数字前面0的个数
            $count_zero = self::count_zero_decimal_less_one($price);
            if ($count_zero <= 4) {
                // 0个数小于等于4
                $number_formate = self::price_display_format($price, 4);
                $number_formate .= " BTC";
            } else {
                // 0个数大于4
                $number_formate = bcmul($price, 100000000, 20);
                $number_formate = self::price_display_format($number_formate, 4);
                $number_formate .= " sat";
            }
        } else {
            // 大于等于1的时候
            $number_formate = self::price_display_format($price, 4);
            $number_formate .= " BTC";
        }

        return $number_formate;
    }

    /**
     * 生成数据树
     * @param array $list 数据列表
     * @param string $id ID
     * @param string $pid 父ID
     * @param string $son 子数据
     * @return array
     */
    public static function maketree($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        list($tree, $map) = [[], []];
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }

    /**
     * 父类得到子类
     * @param $list
     * @param int $pid
     * @return array
     */
    public static function get_sub_list($list, $pid = 0)
    {

        $arr = array();
        foreach ($list as $key => $value) {
            if ($value['pid'] == $pid) {
                if ($value['deleted'] == -1) {
                    $arr[] = $value;
                }
                $arr = array_merge($arr, self::get_sub_list($list, $value['id']));
            }
        }
        return $arr;
    }

    /**
     * 处理显示几天前,几小时前,几分钟前
     * @param int $the_time 时间戳
     * @return string
     */
    public static function day_fast_subject($the_time)
    {
        $now_time = time();
        $dur = $now_time - $the_time;
        if ($dur <= 0) {
            return '刚刚';
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 31536000) {//7天内
                            return '1天前';
                        }
                    }
                }
            }
        }
        return '';
    }

    /**
     * @param string|integer|int $num 目标数字 @todo 貌似有问题
     * @param bool $mode 模式[true:金额（默认）,false:普通数字表示]
     * @param bool $sim 使用小写（默认）
     * @return string
     */
    public static function number2chinese($num, $mode = true, $sim = true)
    {

        if (!is_numeric($num)) return '含有非数字非小数点字符！';
        $char = $sim ? array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九')
            : array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        $unit = $sim ? array('', '十', '百', '千', '', '万', '亿', '兆')
            : array('', '拾', '佰', '仟', '', '萬', '億', '兆');
        $retval = $mode ? '元' : '点';
        //小数部分
        if (strpos($num, '.')) {
            list($num, $dec) = explode('.', $num);
            $dec = strval(round($dec, 2));
            if ($mode) {
                $retval .= "{$char[$dec['0']]}角{$char[$dec['1']]}分";
            } else {
                for ($i = 0, $c = strlen($dec); $i < $c; $i++) {
                    $retval .= $char[$dec[$i]];
                }
            }
        }
        //整数部分
        $str = $mode ? strrev(intval($num)) : strrev($num);
        for ($i = 0, $c = strlen($str); $i < $c; $i++) {
            $out[$i] = $char[$str[$i]];
            if ($mode) {
                $out[$i] .= $str[$i] != '0' ? $unit[$i % 4] : '';
                if ($i > 1 and $str[$i] + $str[$i - 1] == 0) {
                    $out[$i] = '';
                }
                if ($i % 4 == 0) {
                    $out[$i] .= $unit[4 + floor($i / 4)];
                }
            }
        }
        $retval = join('', array_reverse($out));
        return $retval;
    }

    /**
     * 获得今天的开始时间和结束时间(时间戳)
     */
    public static function getTodayStartEndTime()
    {
        $year = date("Y");
        $month = date("m");
        $day = date("d");
        $start = mktime(0, 0, 0, $month, $day, $year);//当天开始时间戳
        $end = mktime(23, 59, 59, $month, $day, $year);//当天结束时间戳
        return array('start' => $start, 'end' => $end);
    }

    /**
     * 远程请求函数
     * @author fanhe
     * @param string $url 请求网址
     * @param mixed $post post参数
     * @param string $cookie
     * @param string $cookiejar
     * @param string $referer
     * @return mixed
     */
    public static function vcurl($url, $post = '', $cookie = '', $cookiejar = '', $referer = '')
    {
        $cookiepath = getcwd() . './' . $cookiejar;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT']);
        if ($referer) {
            curl_setopt($curl, CURLOPT_REFERER, $referer);
        } else {
            curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        }
        if ($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if ($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        if ($cookiejar) {
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiepath);
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiepath);
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $tmpInfo = curl_exec($curl);
        curl_close($curl);
        return $tmpInfo;
    }

    /**
     * 验证手机号码是否合法
     * @param string $mobile 手机号码
     * @return bool
     */
    public static function check_mobile($mobile)
    {

        if (self::skip_validation($mobile)) {
            return true;
        }

        $regex = '/^1[3|4|5|6|7|8|9]\d{9}$/';
        return preg_match($regex, $mobile);
    }

    public static function skip_validation($mobile)
    {
        $regex = '/^1000000\d{4}$/';
        return preg_match($regex, $mobile);
    }

    /**
     * 获取本月的开始和结束时间(时间戳)
     * @param string $time
     * @return array
     */
    public static function getThisMonthStartEndTime($time = "")
    {
        if ($time) {
            $date = new Date($time);
        } else {
            $date = new Date();
        }
        $start = $date->firstDayOfMonth();
        $start = strtotime((string)$start);
        $end = $date->lastDayOfMonth();
        $end = strtotime("$end +1 day");
        return array('start' => $start, 'end' => $end - 1);
    }


    /**
     * todo(使用有问题,需要测试) 获取本周的开始和结束时间(时间戳)
     * @param string $time
     * @return array
     */
    public static function getThisWeekStartEndTime($time = "")
    {

        $date = $time ? new \DateTime($time) : new \DateTime();

        // 设置本周第一天
        $date->modify('this week');
        // 本周第一天日期
        $first_day_of_week = $date->format('Y-m-d');
        // 本周第一天时间戳
        $start = strtotime($first_day_of_week);

        // 本周最后一天
        $date->modify('this week +7 days');
        $end_day_of_week = $date->format('Y-m-d');
        $end = strtotime($end_day_of_week) - 1;
        return array('start' => $start, 'end' => $end);
    }

    /**
     * 获取图片并转码为对应格式保存
     * @param string $url_or_path Url或者Path
     * @param string $path_name 绝对保存路径(包含文件名)
     * @param string $type 图片格式
     * @return bool
     * @throws \ImagickException
     */
    public static function imagick_remote_trans_img($url_or_path, $path_name, $type)
    {
        if (!$url_or_path || !$path_name || !$type) {
            return false;
        }
        $get_type = 1;
        if (strpos($url_or_path, "https") !== false) {
            if (strpos($url_or_path, "www.jutuilian.com") !== false) {
                $img = file_get_contents($url_or_path);
            } else {
                $url_or_path = str_replace("https", "http", $url_or_path);
                $img = file_get_contents($url_or_path);
            }
            $get_type = 3;
        } elseif (strpos($url_or_path, "http") !== false) {
            ob_start();
            $context = stream_context_create(
                array(
                    'http' => array(
                        'follow_location' => false // don't follow redirects
                    ))
            );
            readfile($url_or_path, false, $context);
            $img = ob_get_contents();
            ob_end_clean();
        } else {
            if (!file_exists($url_or_path)) {
                return false;
            }
            $img = file_get_contents($url_or_path);
            $get_type = 2;
        }
        // 没有采集到图片, 先用requests处理
        if (!strlen($img)) {
            // 注册Requests
            Requests::register_autoloader();
            $headers = array(
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
            );
            $response = Requests::get($url_or_path, $headers);
            $img = $response->body;
        }
        // 还是没有则彻底失败
        if (!strlen($img)) {
            Log::write("没有获取到图片[$get_type][$url_or_path][" . strlen($img) . "]");
            return false;
        }

        //图片处理类
        $Imagick = new Imagick();

        // 获取图片
        $readImage = $Imagick->readimageblob($img);
        if (!$readImage) {
            Log::write("读取图片失败");
            return false;
        }
        // 获取图片类型
        //$mimeType = $Imagick->getImageMimeType();

        // 设置图片类型
        $Imagick->setimagetype($type);

        // 保存图片
        $writeImage = $Imagick->writeimage($path_name);
        if (!$writeImage) {
            Log::write("保存图片失败");
            return false;
        }

        return $path_name;
    }

    /**
     * 获取远程图片并保存
     * @param $url
     * @param $path
     * @return bool
     */
    public static function get_remote_img($url, $path)
    {
        //去除URL连接上面可能的引号
        //$url = preg_replace( '/(?:^['"]+|['"/]+$)/', '', $url );
        $hander = curl_init();
        $fp = fopen($path, 'wb');
        curl_setopt($hander, CURLOPT_URL, $url);
        curl_setopt($hander, CURLOPT_FILE, $fp);
        curl_setopt($hander, CURLOPT_HEADER, 0);
        curl_setopt($hander, CURLOPT_FOLLOWLOCATION, 1);
        //curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
        curl_setopt($hander, CURLOPT_TIMEOUT, 60);
        curl_setopt($hander, CURLOPT_CONNECTTIMEOUT, 60);
        curl_exec($hander);
        curl_close($hander);
        fclose($fp);
        if (!file_exists($path) || !filesize($path)) {
            return false;
        }
        Return $path;
    }


}